import React from 'react';   
import ReactDOM from 'react-dom';
import FolderStore from "../stores/FolderStore";   
import OptionStore from "../stores/OptionStore";
import ContextMenu from "./ContextMenu";  

    function colsShow(title, colsOption)  {
        var ret = "";       
        _.each(colsOption, function(col){
            if(col.title == title){
                if(!col.show){
                    ret = "hide";
                }
            }
        });
        return ret;
    }
    var FolderListItem = React.createClass({
        getInitialState: function() {
            var node = this.props.node;
            return {        
                selected: false,
                mouseover: false,
                mark: false,
                editable: false,
                mounting : false,
            };
        },   
        componentDidMount: function(){    
            this.state.mounting = true;       
            FolderStore.propertiesChanged(this.onFolderListChanged);      
        },
        componentWillUnmount: function(){         
            FolderStore.propertiesChanged(this.onFolderListChanged, false);                
            this.state.mounting = false;           
        },
        onFolderListChanged: function(event, data){
            if (data.id == this.props.node.id){
                this.forceUpdate();
            }
        },
        handleMouseOver: function() {    
            if (!this.state.mounting) return;
            this.setState({
                mouseover : true
            });
        },
        handleMouseOut: function() {
            if (!this.state.mounting) return;
             this.setState({
                mouseover : false
            });
        },
        markItem: function(bMark){       
            if (!this.state.mounting) return;     
            this.setState({"mark":bMark});              
        },
        onMouseUp: function(event) {
            if (event.button == 2 && event.ctrlKey) return;

            if (event.button == 2){
                if (this.state.selected){
                    return;
                }                
                this.selected(true);
                return;
            }
            if (event.ctrlKey) {
                this.toggleSelected(event);
            } else {
                this.selected(true);
            }
        },
        onDBClick: function() {            
            if (this.props.node.type == "cmis:folder"){
               FolderStore.setCurFolder(this.props.node);
            }   
            else{
                window.previewByDocumentId(this.props.node.id);
            }
        },
        selected : function(bSelected, multiSel){     
            if (!this.state.mounting) return;
            if (bSelected && !multiSel){
                this.props.folderList.clearSelItem();
            }                  
            this.setState({
                selected: bSelected
            });  

            if (bSelected) {
                if (multiSel) {
                    FolderStore.triggerSelectedObject(this.props.node);
                } else {
                    FolderStore.setSelectedObject(this.props.node);
                }
            }
        },
        toggleSelected: function(event) {  
            this.selected(!this.state.selected, event.ctrlKey);
        },        
        startRename: function(){
            if (!this.state.mounting) return;
            var _this = this;
            this.setState({editable: true});
            _.delay(function(){
                $(_this.refs.input).setCursorPosition({index:-1});
            }, 100);

                },
        onKeyUp: function(event){           
            if (event.keyCode == 13){
                this.refs.input.blur();
                event.preventDefault();
            }          
        },
        endRename: function(){
            if (!this.state.mounting) return;
            this.setState({editable: false});
            var newValue = $(this.refs.input).val();
            window.rename(this.props.node, newValue);
            this.props.node.name = newValue;
        },       
        render: function () {
            var node = this.props.node;
            var isFolder = node.type == 'cmis:folder';
           
            var itemStyle = {
                backgroundColor: (this.state.mark) && !this.state.editable? "#d5d5d5": null,
                color: (this.state.mark) && !this.state.editable ? "#ffffff": null,
                cursor:'pointer'
            };                   

            var classes = {
                'fa fa-file-text-o' : !isFolder,
                'fa fa-folder' : isFolder
            };                  
            var nameItem;
            if (this.state.editable){
                nameItem = (<input ref="input" onKeyUp={this.onKeyUp} onBlur={this.endRename} style={{width:'90%'}} defaultValue={node.get("name")}></input>)
            }    
            else{
                 nameItem = (<span>{node.get("name")}</span>)
            }
            return (             
                <tr onDoubleClick ={this.onDBClick} onMouseUp ={this.onMouseUp} className={classNames({'color-blue-e': this.state.selected})} style={itemStyle} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>                 
                    <td className={"width-50 break-word " + colsShow("Name", this.props.colsOption)}><i className={classNames(classes)}></i>{nameItem}</td>
                    <td className={colsShow("Owner", this.props.colsOption)}>{node.get("owner")}</td>
                    <td className={colsShow("Last modified", this.props.colsOption)} >{node.get("time")}</td>
                    <td style={{minWidth:'60px'}} className={colsShow("File size", this.props.colsOption)}>{bytes(node.get("size"))}</td>
                    <td style={{minWidth:'60px'}} className={"width-50 ellipsis " +colsShow("Description", this.props.colsOption)} title={node.get("description")}>{node.get("description")}</td>
                </tr>
            )
        }
    });

export default React.createClass({
        getInitialState: function () {
            return {
                mouseover: false,              
            };
        }, 
        onFolderListChanged: function(event, data) {
            var _this = this;                 
            _.delay(function() {
                if (data && data.action == 'FOLDER_LIST_ADD') {   
                    var items = data.items;      
                    _.each(items, function(item, index) {
                        if (_this.refs[item.id]){
                            var target = $(ReactDOM.findDOMNode(_this.refs[item.id]))                           
                            var $container = $(ReactDOM.findDOMNode(_this.refs.container));                          
                            $container.animate({
                                scrollTop: target.offset().top - target.parent().offset().top
                            }, 500);
                            _this.refs[item.id].markItem(true);  

                        }                   
                    })
                }
            }, 100);     
        },
        onRename: function(event, data){
            if( this.refs[data.id]){
                this.refs[data.id].startRename();
            }
        },
        componentDidMount: function() { 
            var _this = this;        
            FolderStore.folderListChanged(this.onFolderListChanged);
            FolderStore.renameAction(this.onRename)
            $(document).bind("mouseup",function(e){               
                var target  = $(e.target);                
               // if(target.closest("#menu-document").length != 0){
                  //  return;
               // }
                if(target.closest("#class-list").length == 0){                   
                    $("#menu-document").hide();                  
                }
                else if (e.button == 0){       
                    $("#menu-document").hide();  
                }
            })     
           // $(ReactDOM.findDOMNode(this.refs.table)).chromatable();             
        },  
        componentWillUnmount : function(){
            FolderStore.folderListChanged(this.onFolderListChanged, false);
            FolderStore.renameAction(this.onRename, false);
        },             
        componentWillUpdate: function(nextProps){     
            if (this.props.folderId && nextProps.folderId) {           
                if (nextProps.folderId !== this.props.folderId) {
                    _.each(this.refs, function(item) {
                        if (item instanceof FolderListItem) {
                            item.selected(false);
                        }
                    })
                }
        }
        },
        clearMark: function() {
            var _this = this;
            _.each(_this.refs, function(item) {
                if (typeof item.markItem == "function"){
                   item.markItem(false);
                }
            })
        },
        handleClick:function() {
            this.clearMark();
        },          
           
        clearSelItem: function() {
            _.each(this.refs, function(item) {               
                if (item instanceof FolderListItem){
                    if (item.state.selected) {
                        item.selected(false);
                    }
                }
                
            })
        },
        onContextMenu: function(event){              
            event.preventDefault();
            event.stopPropagation();         
            var clientX = event.clientX;
            var clientY = event.clientY;
            _.defer(function(){             
                $("#menu-document").trigger('position', {
                    left: clientX,
                    top: clientY
                })
            }) 
        },  
        checkAll: function(event) {
            _.each(this.refs, function(item){
                if(typeof item.selected == 'function'){
                   item.selected($(event.target).is(':checked'));
                }
            })   
        },
        sort: function(orderBy){
            var orderOption = OptionStore.getOrderOption();
            if(!orderOption || orderOption.orderBy !== orderBy){
                OptionStore.setOrderOption({
                    orderBy: orderBy,
                    order: false
                });               
                return;
            }
            if(orderOption.orderBy == orderBy){
                OptionStore.setOrderOption({
                    orderBy: orderBy,
                    order: !orderOption.order
                });               
                return;
            }          
        },
        render: function () {
            var data = this.props.data;           
            var option = this.props.option;
            var childern = [];        
            var _this = this;
            var orderOption = OptionStore.getOrderOption();
           
            function getSortIcon(orderBy) {
                if (!orderOption) {
                    return "fa-sort";
                }
                return classNames({
                    'fa-sort': orderOption.orderBy != orderBy,
                    'fa-sort-down': orderOption.orderBy == orderBy && !orderOption.order,
                    'fa-sort-up': orderOption.orderBy == orderBy && orderOption.order,
                })
            }
           
            var header = (
                <tr key="header" ref="header">
                    <th className={colsShow("Name", _this.props.colsOption)}><div className="th-inner"><a onClick={this.sort.bind(this, "name")} href="javascript:void(0)" className="color">{i18n.t("Name")}<i style={{marginLeft: '10px'}} className={getSortIcon("name")+" fa"}></i></a></div></th>
                    <th className={colsShow("Owner", _this.props.colsOption)}><div className="th-inner">{i18n.t("Owner")}</div></th>
                    <th className={colsShow("Last modified", _this.props.colsOption)}><div className="th-inner"><a onClick={this.sort.bind(this, "time")} href="javascript:void(0)" className="color">{i18n.t("Last modified")}<i style={{marginLeft: '10px'}} className={getSortIcon("time")+" fa"}></i></a></div></th>
                    <th className={colsShow("File size", _this.props.colsOption)}><div className="th-inner">{i18n.t("File size")}</div></th>
                    <th className={colsShow("Description", _this.props.colsOption)}><div className="th-inner">{i18n.t("Description")}</div></th>
                </tr>
                )
            if (data) {
                data.forEach((node, index)=>{
                    childern.push(<FolderListItem ref={node.get("id")} node={node} colsOption={_this.props.colsOption} key={node.get("id")} folderList={_this}></FolderListItem>)                
                });
            }             
           
            return (               
                    <div id={this.props.id} className="fixed-table-container">
                        <div className="header-background"></div>
                        <div ref="container" className="fixed-table-container-inner">
                            <table ref={"table"} onContextMenu={this.onContextMenu} className="table fil-list-table table-hover">
                                <thead>{header}</thead>
                                <tbody onClick={this.handleClick} id="class-list">{childern}</tbody>    
                            </table>      
                        </div>                               
                        <ContextMenu ref="contextMenu" ></ContextMenu>      
                    </div>
            )
        }
});